﻿using System.Collections.Generic;
using System.Web.Http;
using Umbraco.Core.Persistence;
using Umbraco.Web.Editors;
using Umbraco.Web.Mvc;
using UmbracoExtending.Dealer.Model.Config;
using UmbracoExtending.Dealer.Model.District;

namespace UmbracoExtending.Dealer.Controller
{
    /// <summary>
    /// 后端行政区域统计控制器
    /// </summary>
    [PluginController("UmbracoDealer")]
    public class BackendDistrictController : UmbracoAuthorizedJsonController
    {

        /// <summary>
        /// 行政区域统计
        /// </summary>
        /// <param name="key">键值</param>
        /// <returns></returns>
        [HttpGet]
        public DistrictStatistics Count(string key)
        {
            var db = UmbracoContext.Application.DatabaseContext.Database;
            DistrictStatistics result = new DistrictStatistics();
            string[] param = key.Split('_');
            string code = param[0].Substring(0, 1).ToUpper() + param[0].Substring(1) + "Code";
            var query = new Sql().Select("COUNT(1)").From("[V_umbracoExtendingDealer]")
                .Where(code + "= @0", param[1]);
            result.DealerCount = db.ExecuteScalar<int>(query);
            result.DealerMistakeCount = db.ExecuteScalar<int>(query.Where(" [IsMistake] = @0 ", "y"));
            result.Path = new List<string>() { "-1" };

            var config = this.GetConfig();

            if (param[0].Equals("province"))
            {
                result.Path.Add("province_" + param[1]);
                result.SubDistrictCount = db.ExecuteScalar<int>("SELECT COUNT(*) FROM (SELECT CityCode FROM [V_umbracoExtendingDealer] WHERE ProvinceCode = @0 GROUP BY CityCode ) AS tbtemp", param[1]);
            }
            else
            {
                result.Path = this.GetPath(config, param[1]);
                if (param[0].Equals("city"))
                {
                    result.SubDistrictCount = db.ExecuteScalar<int>("SELECT COUNT(*) FROM (SELECT DistrictCode FROM [V_umbracoExtendingDealer] WHERE CityCode = @0 GROUP BY DistrictCode ) AS tbtemp", param[1]);
                }
            }
            return result;
        }

        /// <summary>
        /// 获取行政区域对象
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private DistrictItem GetDistrict(string code)
        {
            var db = UmbracoContext.Application.DatabaseContext.Database;
            return db.Single<DistrictItem>("SELECT ProvinceCode, ProvinceName, CityCode, CityName, DistrictCode, DistrictName, AliasName FROM [umbracoExtendingDistrict] WHERE [DistrictCode] = @0", code);
        }

        private DealerConfiguration GetConfig()
        {
            var db = UmbracoContext.Application.DatabaseContext.Database;
            return db.Single<DealerConfiguration>("SELECT Id, MapPlatform, MapAppKey, ListView, ShowWarning, SimpleMode, ShowTwoLayers FROM [umbracoExtendingDealerConfig]");
        }

        private List<string> GetPath(DealerConfiguration config, string code)
        {
            List<string> result = new List<string>() { "-1" };
            var district = this.GetDistrict(code);
            result.Add("province_" + district.ProvinceCode);

            if (config.SimpleMode.Equals("y"))
            {
                if (LocalConfiguration.MunicipalityCode.IndexOf(district.ProvinceCode) >= 0)
                {
                    result.Add("district_" + district.DistrictCode);
                }
                else
                {
                    result.Add("city_" + district.DistrictCode);
                }
            }
            else
            {
                result.Add("city_" + district.CityCode);
                result.Add("district_" + district.DistrictCode);
            }
            return result;
        }
    }
}
